#!/bin/bash

# source ~/.config/scripts/fzf-sshscp/servers.sh

PROJECT_ROOT="$HOME/.config/scripts/fzf-sshscp"
# set -a
# PROJECT_ROOT=$(dirname `readlink --canonicalize "${BASH_SOURCE[0]}"`)
# readonly DIR_CONFIG="$HOME/.config/scripts/fzf-sshscp/"
# source ~/.config/scripts/fzf-sshscp/servers.sh
# source "$PROJECT_ROOT/servers.sh"
source "$PROJECT_ROOT/servers.sh"

_preview1() {
    index=$(_index "$1")
    echo  ${targets[index]}
}

_preview2() {
    index=$(_index "$1")
    target="$2"
    [ "$target" = "从本地到远程" ] && echo "scp -r [SOURCE] ${targets[index]}:~"
    [ "$target" = "从远程到本地" ] && echo "scp -r ${targets[index]}:[SOURCE] ."
}

# _cmdstr() {
#     index=$(_index "$1")
#     # echo ${scpcmds[index]} ${targets[index]}
#     echo ${scpcmds[index]}
# }
_scpcmdstr() {
    index=$(_index "$1")
    # echo ${scpcmds[index]} ${targets[index]}
    echo ${scpcmds[index]}
}

_sshcmdstr() {
    index=$(_index "$1")
    # echo ${scpcmds[index]} ${targets[index]}
    echo ${sshcmds[index]} ${targets[index]}
}

_copytext() {
    index=$(_index "$1")
    echo -n ${copytext[index]}
}

_scp() {
    # 默认fzfopt
    # fzfopt='--cycle --header-first --preview-window=bottom:1:wrap,border-up'
    # fzfopt='--cycle --header-first --preview-window=bottom:1:wrap'

    # 选择服务器
    # server=$(_list | fzf $fzfopt --header=请选择服务器 --preview="~/.config/scripts/fzf-sshscp/scp.sh preview1 {}")
    server=$(_list | fzf \
        --cycle \
        --header='请选择服务器（Esc退出）' \
        --header-first \
        --preview="~/.config/scripts/fzf-sshscp/scp.sh preview1 {}" \
        --height=81% \
        --preview-window=bottom:1:wrap
    )
    [[ -z "$server" ]] && exit 0

    # 选择方向
    # target=$(echo -e "从本地到远程\n从远程到本地" | fzf $fzfopt --header=请选择操作 --preview="~/.config/scripts/fzf-sshscp/scp.sh preview2 $server {}" --height=7)
    target=$(echo -e "从本地到远程\n从远程到本地" | fzf \
        --cycle \
        --header='请选择操作（Esc退出）' \
        --header-first \
        --preview="~/.config/scripts/fzf-sshscp/scp.sh preview2 $server {}" \
        --height=81% \
        --preview-window=bottom:1:wrap
    )
    [[ -z "$target" ]] && exit 0

    # 复制密码到剪贴板 
    # echo -e "copy $(_copytext "$server") ..."
    echo -e "copy "$(_preview1 $server)" passwd  ..."
    echo -e "$(_copytext "$server")" | pbcopy  
    echo -e "copy success."

    # 选择文件 PS: 1.sed '/^$/d' 去除空行 2.跳板机无法使用ssh ls指令
    # [ "$target" = "从本地到远程" ] && _source=$(ls | fzf $fzfopt --print-query --header=请选择要上传的文件 --preview="cat {}" --height=10 | sed '/^$/d' | sed -n '$p')
    if [[ "$target" = "从本地到远程" ]]; then
        # _source=$(ls | fzf $fzfopt --print-query --header=请选择要上传的文件 --preview="cat {}" --height=10 | sed '/^$/d' | sed -n '$p')
        _source=$(ls | fzf \
                        --print-query \
                        --cycle \
                        --header-first \
                        --header='请选择要上传的文件（Esc退出）' \
                        --preview="cat {}" \
                        --height=81% \
                    | sed '/^$/d' \
                    | sed -n '$p'
        )
        # 组装命令
        # _cmd="scp -r ${_source/'~'/$HOME} $(_preview1 $server):~"
        _cmd="$(_scpcmdstr "$server") ${_source/'~'/$HOME} $(_preview1 $server):~"
    fi

    # [ "$target" = "从远程到本地" ] && _source=$(ssh $(_preview1 $server) "ls" | fzf $fzfopt --print-query --header=请选择要下载的文件 --height=10 | sed '/^$/d' | sed -n '$p')
    if [[ "$target" = "从远程到本地" ]]; then
        echo -e "下载远程('$(_preview1 $server)')的文件到本地"
        # 打印要执行的命令
        # echo -e 'ssh '$(_preview1 $server)' ls'
        echo -e $(_sshcmdstr "$server") $(_preview1 $server)' ls'

        # 组装命令执行进入远程主机查看文件列表
        _remotehostfiles=$( $(_sshcmdstr "$server") "ls")
        # _source=$(ssh $(_preview1 $server) "ls"  | fzf $fzfopt --print-query --header=请选择要下载的文件 --height=10 | sed '/^$/d' | sed -n '$p')
        _source=$(echo ${_remotehostfiles} | tr ' ' '\n' | fzf \
                                                            --cycle \
                                                            --header-first \
                                                            --preview-window=bottom:1:wrap \
                                                            --print-query \
                                                            --header='请选择要下载的文件' \
                                                            --height=81% \
                                                        | sed '/^$/d' | sed -n '$p'
        )
        # 组装命令
        # _cmd="scp -r $(_preview1 $server):$_source ."
        _cmd="$(_scpcmdstr "$server") $(_preview1 $server):$_source ."
    fi
    # [[ -z "$_source" ]] && exit 0

    # 组装命令
    # [ "$target" = "从本地到远程" ] && _cmd="scp -r ${_source/'~'/$HOME} $(_preview1 $server):~"
    # [ "$target" = "从远程到本地" ] && _cmd="scp -r $(_preview1 $server):$_source ."

    # 选择操作
    # option=$(echo -e "执行命令\n复制命令" | fzf $fzfopt --header=请选择操作 --preview="echo $_cmd" --height=7)
    option=$(echo -e "执行命令\n复制命令" | fzf  \
                                            --cycle \
                                            --header-first \
                                            --preview-window=bottom:1:wrap \
                                            --header='请选择操作（Esc退出）' \
                                            --preview="echo $_cmd" \
                                            --height=81% \
    )
    [[ -z "$option" ]] && exit 0

    # # 复制密码到剪贴板
    # # echo -e "copy $(_copytext "$server") ..."
    # echo -e "copy passwd  ..."
    # echo -e "$(_copytext "$server")" | pbcopy  
    # echo -e "copy passwd success."

    # 执行
    # linux
    # [ "$option" = "复制命令" ] && echo -n $_cmd | xsel -b copy && echo 'copied'
    # [ "$option" = "执行命令" ] && echo 开始执行: $_cmd && eval $_cmd

    # macOS
    [ "$option" = "复制命令" ] && echo -n $_cmd | pbcopy  && echo 'copied'
    [ "$option" = "执行命令" ] && echo 开始执行: $_cmd && eval $_cmd
}

case $1 in
    '') _scp ;;
    preview1) _preview1 "$2" ;;
    preview2) _preview2 "$2" "$3" ;;
    copytext) _copytext "$2" ;;
    # cmdstr) _cmdstr "$2" ;;
    *) scp $* ;;
esac
